package com.example.question.tree.tree1;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Date 2023-07-09
 * @Author Jonathan
 */
public class Code06_104 {


    /**
     * 深度优先遍历 （后序遍历）
     */
    public int maxDepth1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = maxDepth1(root.left);
        int right = maxDepth1(root.right);
        return Math.max(left, right) + 1;
    }

    private int res = 0;

    public int maxDepth3(TreeNode root) {
        preOrder(root, 0);
        return res;
    }

    private void preOrder(TreeNode node, int depth) {
        if (node == null) return;
        res = Math.max(res, depth);
        preOrder(node.left, depth + 1);
        preOrder(node.right, depth + 1);
    }

    /**
     * 宽度优先搜索
     */
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int levels = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            levels++;
        }
        return levels;
    }
    // 迭代深度优先遍历的时候 也可以

}
